<template>
  <el-dialog title="优惠产品"  :close-on-click-modal="false" 
  :visible.sync="show" class="dialog_index dialog_banner dialog_image"
   :before-close="cancle">
      <el-form ref="discountForm" v-loading="loading" class="article_manage_discount_form" :rules="rules" :model="form">
        <el-form-item label="优惠标题：" prop="discount_title">
          <el-input placeholder="优惠标题（非必填项）" v-model="form.discount_title"></el-input>
        </el-form-item>
         <el-form-item label="优惠描述：" prop="discount_description">
          <el-input placeholder="优惠描述（非必填项）" v-model="form.discount_description"></el-input>
        </el-form-item>
        <div v-for="(item,index) in form.data" :key="index" class="discount_form_item">
          <div class="discount_title">
            <p class="discount_priduct_title">优惠产品{{index+1}}</p>
            <p>
              <el-button @click="addDiscountProduct(index)" type="search">添加产品</el-button>
              <el-button @click="delDiscountProduct(index)" v-if="form.data.length !== 1">删除产品</el-button>
            </p>
          </div>
          <div class="discount_priduct">
            <el-image v-if="item.httpImage" :src="item.httpImage"></el-image>
            <div v-else class="el-image_div"></div>
            <div class="discount_product_info">
              <div class="discount_product_two">
                <el-form-item :prop="'data.'+index+'.product_model_name'" :rules="rules.product_model_name">
                  <el-select   placeholder="产品型号名称（必填项）" v-model="item.product_model_name" @focus="getProductModelName"
                  @change="(value) => changeProductModelName(value, index)" @keyup.enter.native="(event)=>getRelatedInfo(event, index)" >
                    <el-option v-for="product in productModelNameList" :key="product.value" :value="product.value" :label="product.label"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item :prop="'data.'+index+'.site_id'" :rules="rules.site_id">
                  <el-select   placeholder="站点（必填项）" v-model="item.site_id" @focus="getSiteList" @change="(event) => changeSite(event, index)"
                    @keyup.enter.native="(event)=>getRelatedInfo(event, index)">
                    <el-option v-for="product in siteList" :key="product.value" :value="product.id" :label="product.label"></el-option>
                  </el-select>
                </el-form-item>
              </div>
              <div class="discount_product_two">
                <el-form-item :prop="'data.'+index+'.attributes'" :rules="rules.attributes">
                  <el-select   placeholder="产品属性（必填项）" v-model="item.attributes" @focus="getAttributesList(item)" 
                  @change="(value) => changeAttributes(value,index)"  @keyup.enter.native="(event)=>getRelatedInfo(event, index)">
                    <el-option v-for="product in item.attributesList" :key="product.value" :value="product.value" :label="product.label"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item  :prop="'data.'+index+'.link'" :rules="rules.link">
                  <el-input placeholder="链接" v-model="item.link"></el-input>
                </el-form-item>
              </div>
              <div class="discount_product_two">
                <el-form-item  class="discount_time" :prop="'data.'+index+'.time'" :rules="rules.time">
                  <el-input placeholder="时间（必填项）" v-model="item.time" prefix-icon="el-icon-date"></el-input>
                  <el-date-picker @change="(value) =>changeTime(value, index)"   v-model="item.timePicker" type="datetimerange"
                  range-separator="至"  :default-time="['00:00:00' , '23:59:59']"  start-placeholder="开始日期" 
                    value-format="yyyy-MM-dd HH:mm" end-placeholder="结束日期" placeholder="时间（必填项）"></el-date-picker>
                </el-form-item>
                <div class="discount_product_price">
                  <el-form-item :prop="'data.'+index+'.original_price'" :rules="rules.original_price">
                    <el-input placeholder="产品原价（必填项）" v-model="item.original_price"></el-input>
                  </el-form-item>
                  <el-form-item  class="inputNumber" :prop="'data.'+index+'.discount'" :rules="rules.discount">
                    <p >%</p>
                    <el-input-number :min="0" :max="100"  placeholder="折扣（必填项）"  controls-position="right" v-model="item.discount " @change="(value) => changeDiscount(value, index)"></el-input-number>
                  </el-form-item>
                </div>
              </div>
              <div class="discount_product_two">
                <el-form-item :prop="'data.'+index+'.promotion_code'"  :rules="rules.promotion_code">
                  <el-input placeholder="优惠码（非必填项）" v-model="item.promotion_code"></el-input>
                </el-form-item>
                <el-form-item  >
                  <el-input placeholder="标题" disabled v-model="item.product_title"></el-input>
                </el-form-item>
              </div>
            </div>
          </div>
        </div> 
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="search" @click="submitForm">保存</el-button>
        <el-button @click="cancle">取消</el-button>
      </span>
  </el-dialog>
  
</template>

<script>
import {  siteSiteList } from '@/api/manage/site.js'
import { productModelNameList, get_product_title } from '@/api/product/productBasic.js'
import { productAttrList } from '@/api/product/productComment.js'
import { articleDiscountProductGet, articleDiscountProductPost, articleDiscountProductInfo } from '@/api/article/article_manage.js'
export default {
  data () {
    return  {
      loading: false,
      imgH: '',
      imgW: '',
      msg: '',
      form: {
        discount_title: '', //优惠标题
        discount_description: '', //优惠描述
        data: [
          {
            site: '',
            product_model_name: '', //产品型号名称 下拉框
            site_id:'', //站点：下拉框选择
            attributes: '', //产品属性 下拉框
            link: '',//.链接
            httpImage: '', //图片
            time: '', //时间
            start_time: '',
            end_time: '',
            promotion_code: '', //优惠码
            discount: 0,//折扣
            original_price: '',//产品原价
            product_image: '',
            product_title: ''
          }
        ]
      },
      rules:{
        discount_title:[
          { min: 0, max: 50, message: '字段优惠标题最多50字符', trigger: 'blur' }
        ],
        discount_description:[
          { min: 0, max: 200, message: '字段优惠描述最多200字符', trigger: 'blur' },
        ],
        product_model_name: [
          { required: true, message: '字段产品型号名称为必填项', trigger: 'change' },
        ],
        site_id: [
          { required: true, message: '字段站点为必填项', trigger: 'change' },
        ],
        time: [
          { required: true, message: '字段时间为必填项', trigger: 'blur' },
        ],
        attributes: [
          { required: true, message: '字段产品属性为必填项', trigger: 'change' },
        ],
        link:[
          { required: true, message: '字段链接为必填项', trigger: 'change' },
        ],
        original_price:[
          { required: true, message: '字段产品原价为必填项', trigger: 'blur' },
        ],
        discount:[
          { required: true, message: '字段折扣为必填项', trigger: 'change' },
        ],
        promotion_code: []
        
      },
      firstTypeList: [],
      timePicker: '',
      siteList: [],
      productModelNameList: [],
      attributesList: []
    }
  },
  props: {
    show: Boolean,
    closeDialog:Function,
    id: Number
  },
  watch: {
    show:function(){
      if(this.show){
        this.loading = true
        this.getDiscountProduct()
      }
    }
  },
  methods: {
    changeDiscount (value, index) {
      console.log(value, index)
    },
    changeProductModelName (value, index) {
      let data =  this.form.data[index]
      data.attributes = ''
      data.attributesList = []
      data.httpImage = ''
      data.link = ''
      data.product_image = ''
      let productModelNameList =  this.productModelNameList
      for ( let i = 0; i < this.productModelNameList.length; i++ ){
        if (value == productModelNameList[i].value){
          data.product_id = productModelNameList[i].product_id
        }
      }
      this.$set(this.form.data,index, data)
      this.getRelatedInfo(value, index)
      this.getProductTitle(index)

    },
    getProductTitle (index) {
      let data = this.form.data[index]
      if (data.product_model_name && data.site_id) {
        let params = {
          product_model_name: data.product_model_name,
          site_id: data.site_id,
        }
        get_product_title(params).then(res=>{
          if (res.state == 1){
            data.product_title = res.data
            this.$set(this.form.data, index, data)
          }
        }) 
      } 

    },

    editDiscountProduct () {
      let params  = {
        discount_title: this.form.discount_title || '',
        discount_description: this.form.discount_description || '',
        article_id: this.form.article_id,
        data: JSON.stringify(this.form.data)
      }
      articleDiscountProductPost(params).then(res=>{
        if(res.state == 1){
          this.$message.success('保存成功')   
          this.cancle()
        }
      })
    },
    getDiscountProduct () {
      let params = {
        article_id: this.id
      }
      articleDiscountProductGet(params).then(res=>{
        if (res.state == 1){
          let list = res.data
          let data = list.data
          for (let i = 0; i < data.length; i++){
            if (!data[i].discount){
              data[i].discount = undefined
            }
            if (data[i].start_time && data[i].end_time ) {
              data[i].time = data[i].start_time.split(' ')[0] +' - '+data[i].end_time.split(' ')[0]
              data[i].timePicker = []
              data[i].timePicker.push( data[i].start_time)
              data[i].timePicker.push( data[i].end_time)
            } else {
              data[i].time = ''
              data[i].timePicker = []
            }
           
            data[i].attributesList = []
            if (data[i].site_id && data[i].product_model_name){
              this.getProductAttrList(data[i])
            } 
          }
          list.data = data
          this.form = list
          
        }
        this.getSiteList()
        this.loading = false
        this.$refs.discountForm.resetFields(); 
      })
    },

    getRelatedInfo (event,index) {
      let data = this.form.data[index]
      if (data.product_model_name && data.site_id && data.attributes) {
        let params = {
          product_model_name: data.product_model_name,
          site_id: data.site_id,
          attributes: data.attributes,
          product_id: data.product_id
        }
        articleDiscountProductInfo(params).then(res=>{
          if (res.state == 1){
            data.httpImage = res.data.httpImage
            data.product_image = res.data.image
            data.link = res.data.amazon_buy_link
            console.log(data)
            this.$set(this.form.data, index, data)
          }
        }) 
      } 
      
    },
    changeAttributes (value, index) {
      let data = this.form.data[index] 
      if (data.product_model_name && data.site_id) {
        this.getRelatedInfo(null, index)
      }
    },
    changeSite (value, index){
      let siteList =  this.siteList
      let data = this.form.data[index] 
      for ( let i = 0; i < this.siteList.length; i++ ){
        if (value == siteList[i].id){
          data.site = siteList[i].value
        }
      }
      data.attributes = ''
      data.attributesList = []
      data.httpImage = '',
      data.product_image = ''
      data.link = ''
      this.$set(this.form.data, index, data)
      if (data.product_model_name && data.site_id) {
        this.getRelatedInfo(null, index)
        this.getProductTitle(index)
      }
    },
    getAttributesList (data) {
      let name = data.product_model_name
      let site = data.site_id
      if(name && site){
        this.getProductAttrList(data)
      }else {
        this.$message.error('未选择产品型号名称+站点，不可选择产品属性')
      }
    },
    getProductAttrList (data) {
      let params = {
        site_id: data.site_id,
        product_model_name: data.product_model_name
      }
      productAttrList(params).then(res=>{
        if (res.state == 1){
          data.attributesList= res.data
        }
      })
    },
    getProductModelName () {
      productModelNameList().then(res=>{
        if(res.state ==1){
          this.productModelNameList = res.data
        }
      })
    },
    getSiteList(){ //站点
      siteSiteList().then(res=>{
        this.siteList = res.data
      })
    },
    addDiscountProduct (index) {
      let list  = this.form.data
      let obj = {
        product_model_name: '', //产品型号名称 下拉框
        site:'', //站点：下拉框选择
        attributes: '', //产品属性 下拉框
        link: '',//.链接
        httpImage: '', //图片
        time: '', //时间
        start_time: '',
        end_time: '',
        promotion_code: '', //优惠码
        discount: undefined,//折扣
        riginal_price: '',//产品原价
        attributesList: []
      }
      list.splice(index+1, 0, obj)
    },
    delDiscountProduct (index) {
      let list  = this.form.data
      list.splice(index, 1)
    },
    changeTime (arr, i) {
      let data = this.form.data[i]
      if(arr){
        data.time = arr[0]+' - '+arr[1]
        data.start_time = arr[0]
        data.end_time = arr[1]
      }else {
        data.time = ''
        data.start_time = ''
        data.end_time = ''
      }
      this.$set(this.form.data, i, data)
    },
    getFirstType () {},
    submitForm () {
     this.$refs.discountForm.validate((valid) => {
        console.log(valid)
        if (valid) {
          this.editDiscountProduct()
        }
      })
    },
    cancle(){
      // this.$refs.addSiteFrom.clearValidate();
      this.$refs.discountForm.resetFields(); // 清空原来的数据
      this.$emit('closeDialog')
      this.timePicker = ''

    },
  }
}
</script>

<style>

</style>